/**
 * @Description: 秒杀活动
 * @author ourslookAdmin
 * @date 2019-07-29 10:57:53
 */
import React, {Fragment} from 'react';
import {
  BackTop,
  Button,
  Card,
  Checkbox,
  Col,
  DatePicker,
  Divider,
  Form,
  Icon,
  Input,
  InputNumber,
  notification,
  Radio,
  Row,
  Select,
  Spin,
  Switch,
  Table,
  Tag,
  Tooltip,
  Upload,
} from 'antd';
import {formatMessage, FormattedMessage} from 'umi/locale';
import 'antd/dist/antd.css';
import PropTypes from 'prop-types';
import {connect} from 'dva';
import Modal from 'drag-modal';
import {requestLists, requestPromise} from '@/utils/request';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import moment from 'moment';
import BaseForm from '../../../components/ourslook/BaseForm';
import ETable from '../../../components/ourslook/ETable';
import {getWebPath} from '../../../utils/request';
import uiUtils, {hasPermission, rulesReg} from '../../../utils/uiUtils';
import styles from '../../../utils/ourslook.less';
import DefaultImage from '../../../components/ourslook/DefaultImage';

const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;
const TextArea = Input.TextArea;
const Password = Input.Password;
const CheckboxGroup = Checkbox.Group;
const {RangePicker} = DatePicker;

const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

// @coming({ title: '精彩即将呈现！', value: Date.now() + 1000 * 60 * 60 * 24 * 2 })
@connect(() => ({}))
class Seckill extends React.Component {
  params = {
    page: 1,
    limit: 10,
  };

  formItemLayout = {
    labelCol: {span: 5},
    wrapperCol: {span: 19},
  };

  /**
   * https://ant-design.gitee.io/components/table-cn/
   *
   * 需要指定 column 的 width 属性，否则列头和内容可能不对齐。（必须留一列不设宽度或者minWidth以适应弹性布局）
   * 建议指定 scroll.x 为大于表格宽度的固定值或百分比。注意，且非固定列宽度之和不要超过 scroll.x, 一般无table正常展开的宽度
   * 未知长度字段或者字符特别多的字段不要放置在列表
   */
  columns = [
    {
      title: '',
      width: 30,
      align: 'center',
      fixed: 'left',
      render: (value, record, index) => index + 1,
    },
    {
      title: '活动名称',
      dataIndex: 'seckillName',
      width: 120,
      align: 'center',
      sorter: false,
      key: 'seckill_name',
    },
    {
      title: '有效时间',
      dataIndex: 'startTime',
      width: 350,
      align: 'center',
      sorter: false,
      key: 'start_time',
      render: (value, record, index) => `${value}至${record.endTime}`,
    },
    {
      title: '活动标签',
      dataIndex: 'tag',
      width: 120,
      align: 'center',
      sorter: false,
      key: 'tag',
    },
    {
      title: '每人限购',
      dataIndex: 'limitNum',
      // width: 120,
      align: 'center',
      sorter: false,
      key: 'limit',
    },
    {
      title: '活动状态',
      dataIndex: 'voStartStatus',
      width: 120,
      align: 'center',
      sorter: false,
      key: 'vo_start_status',
      render: (value, record, index) => {
        let status = '';
        if (record.status === 1) {
          const startTime = moment(record.startTime).format('X');
          const endTime = moment(record.endTime).format('X');
          const nowTime = moment().format('X');
          if (startTime < nowTime && nowTime < endTime) {
            status = (
              <Tag style={{cursor: 'default'}} className={styles.label_success}>
                正在进行中
              </Tag>
            );
          } else if (endTime < nowTime) {
            status = (
              <Tag style={{cursor: 'default'}} className={styles.label_warning}>
                已结束
              </Tag>
            );
          } else if (nowTime < startTime) {
            status = (
              <Tag style={{cursor: 'default'}} className={styles.label_primary}>
                未开始
              </Tag>
            );
          } else {
            status = (
              <Tag style={{cursor: 'default'}} className={styles.label_danger}>
                已失效
              </Tag>
            );
          }
        } else if (record.status === 0) {
          status = (
            <Tag style={{cursor: 'default'}} className={styles.label_danger}>
              已失效
            </Tag>
          );
        } else {
          status = '- -';
        }
        return status;
      },
    },
    // {
    //   title: '订单实付金额',
    //   dataIndex: 'voOrderTotalMoney',
    //   width: 120,
    //   align: 'center',
    //   sorter: false,
    //   key: 'vo_order_total_money',
    //   render: (value, record, index) => {
    //     if (!value) {
    //       return '- -';
    //     }
    //     return value;
    //   },
    // },
    // {
    //   title: '付款订单数',
    //   dataIndex: 'voOrderTotalNum',
    //   width: 120,
    //   align: 'center',
    //   sorter: false,
    //   key: 'vo_order_total_num',
    //   render: (value, record, index) => {
    //     if (!value) {
    //       return '- -';
    //     }
    //     return value;
    //   },
    // },
    // {
    //   title: '付款人数',
    //   dataIndex: 'voOrderTotalUser',
    //   width: 120,
    //   align: 'center',
    //   sorter: false,
    //   key: 'vo_order_total_user',
    //   render: (value, record, index) => {
    //     if (!value) {
    //       return '- -';
    //     }
    //     return value;
    //   },
    // },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 190,
      align: 'center',
      sorter: true,
      key: 'create_time',
    },
    /*{
      title: '自动取消订单时间',
      dataIndex: 'autoCancleTime',
      width: 120,
      align: 'center',
      sorter: false,
      key: 'auto_cancle_time',
    },*/
    // {
    //   title: '活动设置-活动简介<可选>',
    //   dataIndex: 'brief',
    //   width: 120,
    //   align: 'center',
    //   sorter: false,
    //   key: 'brief',
    // },
    // {
    //   title: '活动设置-特色图片<可选>',
    //   dataIndex: 'img',
    //   width: 120,
    //   align: 'center',
    //   sorter: false,
    //   key: 'img',
    // },
    // {
    //   title: '活动设置-排序',
    //   dataIndex: 'sort',
    //   width: 120,
    //   align: 'center',
    //   sorter: false,
    //   key: 'sort',
    // },
    // {
    //   title: '秒杀提醒设置~开启提醒',
    //   dataIndex: 'remindEnable',
    //   width: 120,
    //   align: 'center',
    //   sorter: false,
    //   key: 'remind_enable',
    // },
    // {
    //   title: '秒杀提醒设置~提前提醒时间',
    //   dataIndex: 'remindTime',
    //   width: 120,
    //   align: 'center',
    //   sorter: false,
    //   key: 'remind_time',
    // },
    {
      title: '状态',
      dataIndex: 'status',
      width: 80,
      align: 'center',
      sorter: false,
      fixed: 'right',
      key: 'status',
      render: (value, record, index) => (
        <React.Fragment>
          <div>
            <Switch
              checkedChildren="上架"
              unCheckedChildren="下架"
              onChange={val => {
                this.setStateByTableColume(record, index);
                this.updateStatus(val);
              }}
              checked={value === 1}
            />
          </div>
        </React.Fragment>
      ),
    },
    {
      title: '操作',
      dataIndex: '',
      width: 120,
      align: 'center',
      fixed: 'right',
      render: (value, record, index) => (
        <React.Fragment>
          <a
            onClick={() => {
              this.setStateByTableColume(record, index);
              this.update();
            }}
          >
            <Tooltip title={<FormattedMessage id="ours.curd.list.edit" defaultMessage="编辑"/>}>
              <Icon type="edit"/>
            </Tooltip>
          </a>
          <Divider type="vertical"/>
          <a
            onClick={() => {
              this.setStateByTableColume(record, index);
              this.view();
            }}
          >
            <Tooltip title={<FormattedMessage id="ours.curd.list.info" defaultMessage="查看"/>}>
              <Icon type="info"/>
            </Tooltip>
          </a>
        </React.Fragment>
      ),
    },
  ];

  constructor(props) {
    super(props);
    this.state = {
      showList: 1, //1:显示列表、2:显示新增
      formList: Seckill.getFormList(),
      selectedRows: [],
      selectedIds: [],
      selectedIndexs: [],
      editModalTitle: null,
      editModalType: null,
      editModel: null,
      editModelConfirmLoading: false,
      //其他属性下面书写
    };
  }

  // 筛选条件
  static getFormList = () => [
    {
      type: 'INPUT',
      field: 'seckillName',
      label: '活动名称',
      placeholder: '活动名称',
    },
    {
      type: 'DATE_RANGE',
      field: 'startTime',
      label: '开始时间',
      placeholder: ['开始时间', ''],
    },
    /*{
      type: 'DATE_RANGE',
      field: 'endTime',
      label: '结束时间',
      placeholder: ['结束时间', ''],
    },*/
    {
      type: 'INPUT',
      field: 'tag',
      label: '活动标签',
      placeholder: '活动标签',
    },
    /*{
      type: 'INPUT',
      field: 'voStartStatus',
      label: '活动状态',
      placeholder: '活动状态',
    },*/
    {
      type: 'SELECT',
      field: 'status',
      label: '状态',
      placeholder: '状态',
      list: [{id: '', name: '请选择状态'}, {id: '1', name: '上架'}, {id: '0', name: '下架'}],
    },
    /*{
      type: 'INPUT',
      field: 'remindEnable',
      label: '秒杀提醒设置~开启提醒',
      placeholder: '秒杀提醒设置~开启提醒',
    },*/
    /* {
       type: 'INPUT',
       field: 'status',
       label: '状态',
       placeholder: '状态',
     },*/
  ];

  componentDidMount() {
    this.requestList();
  }

  componentWillUnmount() {
  }

  /**
   * 根据 formItem field 取值 查找formItem
   * @param formItemField obj的field字段
   * @returns 一个对象
   */
  findFormListItemByField = formItemField =>
    this.state.formList.find((value, index, array) => value.field === formItemField);

  query = fieldParams => {
    this.params = JSON.parse(JSON.stringify(Object.assign(this.params, fieldParams)));
    this.requestList();
  };

  add = () => {
    this.setState({
      editModalType: 'add',
      editModalTitle: formatMessage({id: 'ours.curd.list.create'}), //创建
      editModel: {},
      showList: 2,
    });
  };

  update = () => {
    const {selectedRows, selectedIds, selectedIndexs} = this.state;
    if (!selectedRows) {
      uiUtils.showAlert(formatMessage({id: 'ours.curd.show-alert.select-please'}));
      return;
    }
    if (selectedRows.length > 1) {
      uiUtils.showAlert(formatMessage({id: 'ours.curd.show-alert.select-one-please'}));
      return;
    }
    this.setState({
      editModalType: 'update',
      editModalTitle: <FormattedMessage id="ours.curd.list.edit" defaultMessage="编辑"/>,
      editModel: JSON.parse(JSON.stringify(selectedRows[0])),
      showList: 2,
    });
    this.getInfo(selectedRows[0].id);
  };

  view = () => {
    const {selectedRows, selectedIds, selectedIndexs} = this.state;
    if (!selectedRows) {
      uiUtils.showAlert(formatMessage({id: 'ours.curd.show-alert.select-please'}));
      return;
    }
    if (selectedRows.length > 1) {
      uiUtils.showAlert(formatMessage({id: 'ours.curd.show-alert.select-one-please'}));
      return;
    }
    this.setState({
      editModalType: 'view',
      editModalTitle: <FormattedMessage id="ours.curd.list.info" defaultMessage="查看"/>,
      editModel: selectedRows[0],
      showList: 2,
    });
    this.getInfo(selectedRows[0].id);
  };

  del = () => {
    const selectedRows = this.state.selectedRows;
    const ids = [];
    for (let i = 0; i < selectedRows.length; i += 1) {
      ids.push(selectedRows[i].id);
    }

    uiUtils.showConfirm(formatMessage({id: 'ours.curd.show-alert.confirm-delete'}), () => {
      this.setState({
        loading: true,
      });
      requestPromise(`${getWebPath()}promotionsseckill/delete`, {
        method: 'POST',
        body: ids,
      }).then(res => {
        this.setState({
          loading: false,
        });
        if (res && res.code === 0) {
          uiUtils.showMessage(
            formatMessage({id: 'ours.curd.show-alert.operate-success'}),
            'success'
          );
          this.requestList();
        }
      });
    });
  };

  saveOrUpdate = () => {
    const editModalType = this.state.editModalType;
    //不能双向绑定，这里只能原对象、新对象进行合并.
    const promotionsSeckill = Object.assign(
      this.state.editModel,
      this.editForm.props.form.getFieldsValue()
    );
    if (promotionsSeckill.remindEnable === undefined || promotionsSeckill.remindEnable === null) {
      promotionsSeckill.remindEnable = false;
    }
    promotionsSeckill.seckillProductList = this.editForm.state.seckillProductList;
    if (promotionsSeckill.seckillProductList===undefined || promotionsSeckill.seckillProductList.length===0) {
      uiUtils.showMessage("至少有一个商品！", "warning");
      return;
    }

    this.editForm.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        // submit the values
        const url =
          promotionsSeckill.id == null ? '/promotionsseckill/save' : '/promotionsseckill/update';
        //对象删除一个属性
        //delete promotionsSeckill.xxxxPros;
        // promotionsSeckill.brief = promotionsSeckill.brief.toHTML();
        promotionsSeckill.startTime = `${promotionsSeckill.startTimeBetween[0].format(
          'YYYY-MM-DD HH'
        )}:00:00`;
        promotionsSeckill.endTime = `${promotionsSeckill.startTimeBetween[1].format(
          'YYYY-MM-DD HH'
        )}:00:00`;

        this.setState({
          editModelConfirmLoading: true,
        });
        requestPromise(getWebPath() + url, {
          method: 'POST',
          body: promotionsSeckill,
        }).then(res => {
          this.setState({
            editModelConfirmLoading: false,
          });
          if (res && res.code === 0) {
            uiUtils.showMessage(
              formatMessage({id: 'ours.curd.show-alert.operate-success'}),
              'success'
            );
            this.setState({
              showList: 1,
            });

            //新增重新置为第一页
            if (!promotionsSeckill.id) {
              this.params.page = 1;
            }
            this.requestList();
          }
        });
      }
    });
  };

  getInfo = id => {
  };

  setStateByTableColume = (record, index) => {
    this.state = {
      ...this.state,
      selectedRows: [record],
      selectedIds: [record.id],
      selectedIndexs: [index],
    };
  };

  operateByIds = status => {
  };

  //========其他所有的处理方法，请在按照约定进行处理==========

  updateStatus = val => {
    const {selectedRows, selectedIds, selectedIndexs} = this.state;
    if (!selectedRows) {
      uiUtils.showAlert(formatMessage({id: 'ours.curd.show-alert.select-please'}));
      return;
    }
    if (selectedRows.length > 1) {
      uiUtils.showAlert(formatMessage({id: 'ours.curd.show-alert.select-one-please'}));
      return;
    }
    let status;
    if (val) {
      status = 1;
    } else {
      status = -1;
    }
    const ids = [];
    for (let i = 0; i < selectedRows.length; i += 1) {
      ids.push(selectedRows[i].id);
    }

    this.setState({
      loading: true,
    });
    //const data = 'modelIds=' + ids.join(',') + '&status=' + status;
    const data = {
      modelIds: ids.join(','),
      status,
    };
    requestPromise(`${getWebPath()}promotionsseckill/operatePromotionsSeckillByIds`, {
      method: 'POST',
      contentType: 'application/x-www-form-urlencoded',
      body: data,
    }).then(res => {
      this.setState({
        loading: false,
      });
      if (res && res.code === 0) {
        uiUtils.showMessage(
          formatMessage({id: 'ours.curd.show-alert.operate-success'}),
          'success'
        );
        this.requestList();
      }
    });
  };

  /**
   * 表格 筛选和排序 回调
   */
  filtersSorterChange = tableParams => {
    this.params = JSON.parse(JSON.stringify(Object.assign(this.params, tableParams)));
    this.requestList();
  };

  requestList = () => {
    requestLists(this, `${getWebPath()}promotionsseckill/list`, this.params);
  };

  vShow = showListNum => ({display: this.state.showList === showListNum ? 'block' : 'none'});

  render() {
    const style = {
      style: {
        marginLeft: 10,
        marginTop: 10,
      },
      disabled: this.state.selectedIndexs.length <= 0,
    };

    /* eslint-disable react/jsx-no-bind */
    return (
      <PageHeaderWrapper title="">
        <Card
          bordered={false}
          style={{...this.vShow(1)}}
          className={styles.oursCard}
          bodyStyle={{padding: '20px'}}
        >
          <BaseForm
            formList={this.state.formList}
            loading={this.state.loading}
            filterSubmit={this.query}
          />

          <Fragment>
            <Button
              type="primary"
              icon="plus"
              onClick={this.add}
              hidden={!hasPermission('promotionsseckill:save')}
            >
              <FormattedMessage id="ours.curd.list.add" defaultMessage="新增"/>
            </Button>
            <Button
              type="danger"
              icon="delete"
              {...style}
              onClick={this.del}
              hidden={!hasPermission('promotionsseckill:delete')}
            >
              <FormattedMessage id="ours.curd.list.delete" defaultMessage="删除"/>
            </Button>
          </Fragment>

          <div className="content-wrap">
            <ETable
              onSelectRow={uiUtils.onSelectRow.bind(this)}
              primaryKey="id"
              selectedIndexs={this.state.selectedIndexs}
              selectedRows={this.state.selectedRows}
              selectedIds={this.state.selectedIds}
              onChange={this.filtersSorterChange}
              columns={this.columns}
              dataSource={this.state.list}
              pagination={this.state.pagination}
              loading={this.state.loading}
              scroll={{x: 1600}}
            />
          </div>
        </Card>

        <BackTop/>

        <Spin spinning={this.state.editModelConfirmLoading} delay={10}>
          {//返回null,这里对不用的组件进行销毁
            this.state.showList === 1 ? null : (
              <Card
                title={this.state.editModalTitle}
                bordered={false}
                actions={[
                  <div>
                    <React.Fragment>
                      <Button
                        type="primary"
                        hidden={this.state.editModalType === 'view'}
                        style={{marginRight: '18px'}}
                        onClick={this.saveOrUpdate}
                      >
                        <FormattedMessage id="ours.curd.add.save" defaultMessage="保存"/>
                      </Button>
                      <Button
                        style={{marginRight: '18px'}}
                        onClick={() => {
                          this.editForm.props.form.resetFields();
                          this.setState({showList: 1});
                        }}
                      >
                        <FormattedMessage id="ours.curd.add.back" defaultMessage="返回"/>
                      </Button>
                    </React.Fragment>
                  </div>,
                ]}
                style={{...this.vShow(2)}}
                bodyStyle={{padding: '20px'}}
                ref={node => {
                  this.container = node;
                }}
              >
                <EditForm
                  type={this.state.editModalType}
                  model={this.state.editModel}
                  wrappedComponentRef={inst => {
                    this.editForm = inst;
                  }}
                />
              </Card>
            )}
        </Spin>
      </PageHeaderWrapper>
    );
  }
}

export default Seckill;

/**
 * 添加商品
 */
@Form.create()
class ProductAddForm extends React.Component {
  static propTypes = {
    visible: PropTypes.bool,
    onCancel: PropTypes.func,
    onOk: PropTypes.func,
    seckillProductList: PropTypes.object,
  };

  static defaultProps = {
    visible: false,
    onCancel: () => {
    },
    onOk: () => {
    },
    seckillProductList: []
  };

  constructor(props) {
    super(props);
    this.state = {};
    this.productSearch();
  }

  productSearch = () => {
    const productIds = [];
    if (this.props.seckillProductList) {
      const seckillProductList = this.props.seckillProductList;
      for (let i = 0; i < seckillProductList.length; i++) {
        productIds.push(seckillProductList[i].productId);
      }
    }
//&seckillProductIds=${productIds}
    requestPromise(getWebPath(`/mailproduct/list?not_IN_pom=1&status=2`), {
      method: 'GET',
    }).then(res => {
      if (res && res.code === 0) {
        const datas = res.page.list || [];
        const results = [
          <Option key="" value="">
            {'请选择商品'}
          </Option>,
        ];
        datas.forEach(r => {
          // if (r.id !== this.props.model.productId) {
          results.push(
            <Option key={r.id} value={r.id}>
              {r.productName}
            </Option>
          );
          // }
        });
        this.setState({
          productOptions: results,
        });
      }
    });
  };

  requestSpecList = productId => {
    requestPromise(
      `${getWebPath(
        `/mailproductspec/list?not_IN_otherSeckillProduct=1&not_IN_pom=1&productId=${productId === undefined ? '' : productId}`
      )}`,
      {
        method: 'GET',
      }
    ).then(res => {
      if (res && res.code === 0) {
        const results = res.page.list;
        const datas = [];
        results.forEach(r => {
          const data = {
            key: r.id,
            name: this.specsParse(r.productSpecs),
            value: r.productSpecs,
            price: r.price,
            inventory: r.inventory,
          };
          datas.push(data);
        });

        const specDataOptions = [
          <Option key="" value="">
            请选择规格
          </Option>,
        ];
        datas.forEach(r => {
          specDataOptions.push(
            <Option key={r.key} value={r.key}>
              规格：{r.name}--价格：{r.price}
            </Option>
          );
        });

        this.setState({
          // eslint-disable-next-line object-shorthand
          specDataOptions: specDataOptions,
          specDatas: datas
        });
        return datas;
      }
    });
  };

  /**
   * 解析规格
   * @param specs
   */
  specsParse = specs => {
    if (specs === null || specs === undefined || specs==='') {
      return '默认规格';
    }
    const productSpecs = JSON.parse(specs);
    let productss = '';
    productSpecs.forEach(s => {
      // eslint-disable-next-line guard-for-in,no-restricted-syntax
      for (const key in s) {
        productss = productss === '' ? s[key] : `${productss},${s[key]}`;
      }
    });
    return productss;
  };

  getPropsByKey = prop => {
    const model = this.props.model || {};
    const finalModel = Object.assign(model, this.props.form.getFieldsValue());
    return finalModel[prop];
  };

  render() {
    const visible = this.props.visible;
    const onCancel = this.props.onCancel;
    const onOk = this.props.onOk;
    const model = this.props.model || {};
    const {
      form,
      form: {getFieldDecorator, getFieldValue, setFieldsValue},
    } = this.props;
    const formItemLayout = {
      labelCol: {span: 5},
      wrapperCol: {span: 18}, //5+19=24,少一个栅格
    };
    const colSpanLayout = {md: 12, sm: 24}; //每一col跨?列
    const rowGutterPxLayout = {md: 24, sm: 16}; //col之间的间隔?px

    return (
      <Modal
        title="添加商品"
        width={1000}
        visible={visible}
        onCancel={() => {
          onCancel();
        }}
        onOk={() => {
          this.props.form.validateFieldsAndScroll((err, values) => {
            if (!err) {
              const seckillProductList = Object.assign(model, this.props.form.getFieldsValue());
              seckillProductList.productName = this.state.productName;
              seckillProductList.price = this.state.price;
              // console.log(seckillProductList);

              if (this.state.currentOldInventory) {
                const temp = this.state.currentOldInventory;

                if (Number.parseFloat(seckillProductList.seckillPrice) > Number.parseFloat(temp.price)) {
                  notification.warning({
                    message: 'Notification Title',
                    description: '秒杀价格，不能大于原始价格！',
                  });
                  return;
                }
                if (seckillProductList.totalSeckillStock > temp.inventory) {
                  notification.warning({
                    message: 'Notification Title',
                    description: '秒杀库存，不能大于原有库存！',
                  });
                  return;
                }
              }
              onOk(seckillProductList);
            }
          });
        }}
      >
        <Card bordered bodyStyle={{paddingBottom: 10}} style={{marginBottom: 20}}>
          <Row gutter={{...rowGutterPxLayout}}>
            <Col {...colSpanLayout}>
              <FormItem label="请选择商品" {...formItemLayout}>
                {getFieldDecorator('productId', {
                  initialValue: '',
                  rules: [
                    {
                      required: true,
                      message: '商品必填',
                    },
                  ],
                })(
                  <Select
                    showSearch
                    style={{width: 460}}
                    placeholder="请选择商品"
                    optionFilterProp="children"
                    onChange={(value, option) => {
                      console.log(option.props.children);
                      this.setState({productName: option.props.children});
                      this.props.form.setFieldsValue({specId: null});
                      if (value === undefined || value === null || value === '') {
                        //
                      } else {
                        this.requestSpecList(value);
                      }
                    }}
                    notFoundContent={null}
                  >
                    {this.state.productOptions}
                  </Select>
                )}
              </FormItem>
            </Col>
          </Row>

          <Row gutter={{...rowGutterPxLayout}}>
            <Col {...colSpanLayout}>
              <FormItem label="请选择规格" {...formItemLayout}>
                {getFieldDecorator('specId', {
                  // initialValue: "",
                  rules: [
                    {
                      required: true,
                      message: '规格必填',
                    },
                  ],
                })(
                  <Select
                    showSearch
                    style={{width: 300}}
                    placeholder="请选择规格"
                    optionFilterProp="children"
                    notFoundContent={null}
                    onChange={(value, option) => {
                      // console.log(value);
                      console.log(option.props.children);
                      // const temp = option.props.children.toString().split("价格：");
                      // if (temp.length !== 1) {
                      //   this.setState({price: temp[1]});
                      // }

                      if (option.props.children.length === 4) {
                        this.setState({price: option.props.children[3]});
                      }
                      // console.log(this.state.specDatas);
                      // eslint-disable-next-line
                      const inventory = this.state.specDatas.filter(value1 => value1.key === value)[0];
                      this.setState({currentOldInventory: inventory});
                      console.log(inventory);
                    }}
                  >
                    {this.state.specDataOptions}
                  </Select>
                )}
              </FormItem>
            </Col>

            <Col {...colSpanLayout}>
              <FormItem label="秒杀价格" {...formItemLayout}>
                {getFieldDecorator('seckillPrice', {
                  initialValue: model.seckillPrice,
                  rules: [
                    {
                      required: true,
                      message: '请输入秒杀价格',
                    },
                    rulesReg('money_0_999999'),
                  ],
                })(<Input style={{width: '300px'}} placeholder="秒杀价格"/>)}
              </FormItem>
            </Col>

            <Col {...colSpanLayout}>
              <FormItem
                label="秒杀库存"
                {...formItemLayout}
                extra={this.state.currentOldInventory ? `当前库存：${this.state.currentOldInventory.inventory}` : ''}>
                {getFieldDecorator('totalSeckillStock', {
                  initialValue: model.totalSeckillStock,
                  rules: [
                    {
                      required: true,
                      message: '秒杀库存必填',
                    },
                    rulesReg('busInt'),
                  ],
                })(
                  <InputNumber
                    style={{width: '300px'}}
                    min={1}
                    max={999999}
                    autocomplete="off"
                    placeholder="秒杀库存"
                  />
                )}
              </FormItem>
            </Col>

            <Col {...colSpanLayout}>
              <FormItem label="排序" {...formItemLayout}>
                {getFieldDecorator('sort', {
                  initialValue: model.sort === undefined ? 1 : model.sort,
                  rules: [
                    {
                      required: true,
                      message: '排序必填',
                    },
                    rulesReg('plus'),
                  ],
                })(
                  <Input
                    style={{width: '300px'}}
                    type="text"
                    maxLength={9}
                    autocomplete="off"
                    placeholder="排序"
                  />
                )}
              </FormItem>
            </Col>
          </Row>
        </Card>
      </Modal>
    );
  }
}

/**
 *  新增、编辑、复制、查看的Form
 */

/* eslint react/no-multi-comp:0 */
class EditForm extends React.Component {
  static propTypes = {
    type: PropTypes.string, //form类型，可选值：add（增加）、update（修改）、copy（复制）、view（查看）、
    model: PropTypes.object, //数据模型model，对应后台的model
  };

  static defaultProps = {
    type: '', //表单布局数组
    model: null,
  };

  constructor(props) {
    super(props);
    const defaultImgList = this.props.model.img
      ? [
        {
          uid: '1',
          name: '',
          status: 'done',
          url: this.props.model.img,
        },
      ]
      : null; //defaultFileList
    this.state = {
      seckillProductList: [],
      previewVisible: false, //上传文件预览
      previewImage: '', //上传文件预览
      defaultImgList, //上传文件列表
      fileImgList: defaultImgList && defaultImgList.length > 0 ? [defaultImgList[0]] : [],
    };
  }

  componentDidMount() {
    if (this.props.model.id !== undefined && this.props.model.id !== null) {
      this.getInfo(this.props.model.id);
    }
  }

  /**
   * 生命周期-属性发生变化...componentWillReceiveProps
   * 这里的nextProps，可以获取到所有的属性。
   * 目前没用，因为 dialog 每次都被销毁了
   */
  componentWillReceiveProps(nextProps) {
    if (nextProps.model) {
      // this.state = {};
      // //使用setFieldsValue实现修改form value的值，不用使用 this.setState({});
      // this.props.model.xxx = 'value';
      // this.props.form.setFieldsValue({xxx: 'value'});
    }
  }

  getPropsByKey = prop => {
    const model = this.props.model || {};
    const finalModel = Object.assign(model, this.props.form.getFieldsValue());
    return finalModel[prop];
  };

  disabledDate = current => {
    //前一天
    return current && current < moment().endOf('day').subtract(1, 'days');
  };

  disabledTime = (dats, type) => {
    //限制开始时间
    if (type === 'start' && dats[0].isBefore(moment())) {
      const arr = this.range(0, new Date().getHours());
      return {
        disabledHours: () => arr,
      };
    }
    return {
      disabledHours: () => [],
    };
  };

  range = (start, end) => {
    const result = [];
    for (let i = start; i < end; i++) {
      result.push(i);
    }
    return result;
  };

  handleUploadOnRemove = file => {
    // console.log(this.state);
    // console.log(this.props.model);
    this.props.form.setFieldsValue({
      img: undefined,
    });
    this.setState({
      fileImgList: [],
    });
  };

  /**
   *
   * @param info
   */
  handleUploadOnChange = info => {
    const {loadingCallback} = this.props;
    // 状态有：uploading done error removed
    if (info.file.status === 'done') {
      uiUtils.showMessage(`${info.file.name} 文件上傳成功.`, 'success');
      //这个Upload组件比较特殊，这里在OnChange方法手工设置value,不做延迟，就设置不了被覆盖了。
      const response = info.fileList[0].response;
      this.setState({
        fileImgList: info.fileList,
      });
      if (response) {
        if (response.code === 0) {
          setTimeout(() => {
            this.props.form.setFieldsValue({
              img: response.object,
            });
            if (loadingCallback) {
              loadingCallback(false);
            }
          }, 500);
        } else {
          uiUtils.showAlert(response.msg, 'error');
          if (loadingCallback) {
            loadingCallback(false);
          }
        }
      }
    } else if (info.file.status === 'error') {
      if (loadingCallback) {
        loadingCallback(false);
      }
      uiUtils.showMessage(`${info.file.name} 文件上傳失敗.`, 'error');
    } else if (info.file.status === 'uploading') {
      if (loadingCallback) {
        loadingCallback(true);
      }
    }
  };

  /**
   * @param file
   */
  handleUploadPreview = file => {
    const previewImage = file.url || file.thumbUrl;
    const previewVisible =
      previewImage.toLowerCase().endsWith('.bpm') ||
      previewImage.toLowerCase().endsWith('.png') ||
      previewImage.toLowerCase().endsWith('.jpg') ||
      previewImage.toLowerCase().endsWith('.jpeg') ||
      previewImage.toLowerCase().endsWith('.gif') ||
      file.type.startsWith('image/');
    this.setState({
      previewImage,
      previewVisible,
    });
  };

  showProductAddFrom = () => {
    this.setState({productAddFromVisible: true});
  };

  /**
   * 删除操作
   * @param index
   */
  delSeckillProduct = index => {
    let datasources = this.state.seckillProductList;
    if (datasources === undefined) {
      datasources = [];
    }
    const newdataSources = [];
    datasources.forEach((value, index1) => {
      if (index1 !== index) {
        newdataSources.push(datasources[index1]);
      }
    });
    this.setState({
      seckillProductList: newdataSources,
    });
  };

  getInfo = id => {
    requestPromise(getWebPath(`promotionsseckill/info/${id}`), {
      method: 'GET',
    }).then(res => {
      if (res && res.code === 0) {
        this.setState({
          seckillProductList: res.promotionsSeckill.seckillProductList,
        });
      }
    });
  };

  render() {
    const type = this.props.type; //编辑是：新增（add）、编辑(edit)、复制(copy)、还是查看(view)
    const model = this.props.model || {};
    const {
      form,
      form: {getFieldDecorator, getFieldValue, setFieldsValue},
    } = this.props;
    const formItemLayout = {
      labelCol: {span: 5},
      wrapperCol: {span: 18}, //5+19=24,少一个栅格
    };
    const colSpanLayout = {md: 12, sm: 24}; //每一col跨?列
    const rowGutterPxLayout = {md: 24, sm: 16}; //col之间的间隔?px
    const inputCodeDisabled = {
      disabled: type === 'update',
    };
    const inputCodeDisabledForView = {
      readonly: type === 'view',
    };

    const uploadPropsImg = {
      action: `${getWebPath('/api/fileUpload')}`,
      name: 'myfile',
      data: {moduleName: 'draw', isImage: true, acceptFileExts: 'image'},
      withCredentials: true,
      headers: {
        authorization: 'authorization-text',
      },
      onChange: this.handleUploadOnChange,
      onRemove: this.handleUploadOnRemove,
      defaultFileList: this.state.defaultImgList,
      multiple: false,
      accept: '.jpg, .jpeg, .png, .bmp, ', //image/*
    };
    const uploadButton = (
      <div>
        <Icon type="plus"/>
        <div className="ant-upload-text">上传</div>
      </div>
    );

    //展示
    const columns = [
      {
        title: '商品名称',
        dataIndex: 'productName',
        key: 'productName',
      },
      {
        title: '商品原价',
        dataIndex: 'price',
        key: 'price',
      },
      // {
      //   title: '商品原价',
      //   dataIndex: 'originalPrice',
      //   key: 'originalPrice',
      // },
      {
        title: '秒杀价格',
        dataIndex: 'seckillPrice',
        key: 'seckillPrice',
      },
      {
        title: '库存',
        dataIndex: 'totalSeckillStock',
        key: 'total_seckill_stock',
      },
      {
        title: '操作',
        key: '',
        dataIndex: '',
        width: 100,
        fixed: 'right',
        render: (value, record, index) => (
          <React.Fragment>
            <a
              hidden={this.props.type === 'view'}
              onClick={() => {
                if (type === 'view') {
                  console.log('这是查看哦！');
                } else {
                  this.delSeckillProduct(index);
                }
                console.log(value);
                console.log(record);
              }}
            >
              <Tooltip
                title={<FormattedMessage id="ours.curd.list.delete" defaultMessage="删除"/>}
              >
                <Icon type="delete"/>
              </Tooltip>
            </a>
          </React.Fragment>
        ),
      },
    ];

    //校验文档：https://ant.design/components/form-cn/#%E6%A0%A1%E9%AA%8C%E8%A7%84%E5%88%99
    return (
      <Fragment>
        <Form layout="horizontal">
          <Card
            bordered
            // hoverable
            size="small"
            bodyStyle={{paddingBottom: 10}}
            style={{marginBottom: 20}}
            title="活动基本信息"
          >
            <Row gutter={{...rowGutterPxLayout}}>
              <Col {...colSpanLayout}>
                <FormItem label="活动名称" {...formItemLayout}>
                  {type === 'view'
                    ? model.seckillName
                    : getFieldDecorator('seckillName', {
                      initialValue: model.seckillName,
                      rules: [
                        {
                          required: true,
                          message: '活动名称必填',
                        },
                        {
                          whitespace: true,
                          message: '不能包含空白符',
                        },
                        {
                          max: 128,
                          message: '最长128个字符',
                        },
                      ],
                    })(
                      <Input
                        type="text"
                        autocomplete="off"
                        maxlength={128}
                        placeholder="活动名称"
                      />
                    )}
                </FormItem>
              </Col>
              <Col {...colSpanLayout}>
                <FormItem label="活动有效期" {...formItemLayout}>
                  {type === 'view'
                    ? `${model.startTime}~${model.endTime}`
                    : getFieldDecorator('startTimeBetween', {
                      initialValue: [
                        moment(
                          model.startTime === undefined ? moment() : model.startTime,
                          'YYYY-MM-DD HH'
                        ),
                        moment(
                          model.endTime === undefined ? moment() : model.endTime,
                          'YYYY-MM-DD HH'
                        ),
                      ],
                      rules: [
                        {
                          required: true,
                          message: '活动设置-开始时间必填',
                        },
                      ],
                    })(
                      <RangePicker
                        format="YYYY-MM-DD HH"
                        placeholder={['开始时间', '结束时间']}
                        disabledDate={this.disabledDate}
                        showTime={{format: 'HH'}}
                        // disabledTime={this.disabledTime}
                      />
                    )}
                </FormItem>
              </Col>

              <Col {...colSpanLayout}>
                <FormItem label="活动标签" {...formItemLayout}>
                  {type === 'view'
                    ? model.tag
                    : getFieldDecorator('tag', {
                      initialValue: model.tag,
                      rules: [
                        /*{
                        required: true,
                        message: '活动设置-活动标签必填',
                      },*/
                        {
                          whitespace: true,
                          message: '不能包含空白符',
                        },
                        {
                          max: 32,
                          message: '最长32个字符',
                        },
                      ],
                    })(
                      <Input
                        type="text"
                        autocomplete="off"
                        maxlength={32}
                        placeholder="活动标签"
                      />
                    )}
                </FormItem>
              </Col>
              <Col {...colSpanLayout}>
                <FormItem
                  label="每人限购"
                  extra="限制每个用户购买数量，0为不限制。"
                  {...formItemLayout}>
                  {type === 'view'
                    ? model.limitNum
                    : getFieldDecorator('limitNum', {
                      initialValue: (model.limitNum === undefined || model.limitNum === null) ? 0 : model.limitNum,
                      rules: [
                        {
                          required: true,
                          message: '每人限购必填',
                        },
                        rulesReg('plus'),
                      ],
                    })(<Input type="text" autocomplete="off" placeholder="每人限购数量.0不限购"/>)}
                </FormItem>

              </Col>
              <Col {...colSpanLayout}>
                <FormItem label="自动取消时间" {...formItemLayout}>
                  {type === 'view'
                    ? model.autoCancleTime
                    : getFieldDecorator('autoCancleTime', {
                      initialValue: model.autoCancleTime,
                      rules: [
                        {
                          required: true,
                          message: '自动取消时间必填',
                        },
                        rulesReg('plus'),
                      ],
                    })(
                      <Input
                        type="text"
                        autocomplete="off"
                        placeholder="自动取消订单时间(单位分钟)"
                      />
                    )}
                </FormItem>
              </Col>

              <Col {...colSpanLayout}>
                <FormItem label="排序" {...formItemLayout}>
                  {type === 'view'
                    ? model.sort
                    : getFieldDecorator('sort', {
                      initialValue: model.sort,
                      rules: [
                        {
                          required: true,
                          message: '排序必填',
                        },
                        rulesReg('plus'),
                      ],
                    })(<Input type="text" maxLength={9} autocomplete="off" placeholder="排序"/>)}
                </FormItem>
              </Col>
            </Row>

            {/*<Divider orientation="left">Left Text</Divider>*/}
            {/*秒杀提醒*/}
            <Row gutter={{...rowGutterPxLayout}}>
              <Col {...colSpanLayout}>
                <FormItem label="是否开启提醒" {...formItemLayout}>
                  {type === 'view'
                    ? model.remindEnable
                      ? '是'
                      : '否'
                    : getFieldDecorator('remindEnable', {
                      // initialValue: 1,
                      rules: [],
                    })(
                      <Switch
                        checkedChildren="开"
                        unCheckedChildren="关"
                        onChange={(checked, event) => {
                          this.props.model.remindEnable = checked;
                          console.log(model.remindEnable);
                        }}
                        defaultChecked={model.remindEnable}
                      />
                    )}
                </FormItem>
              </Col>
              {model.remindEnable && (
                <Col {...colSpanLayout}>
                  <FormItem label="提前提醒时间" {...formItemLayout}>
                    {type === 'view'
                      ? model.remindTime
                      : getFieldDecorator('remindTime', {
                        initialValue: model.remindTime,
                        rules: [
                          {
                            required: true,
                            message: '提前提醒时间必填',
                          },
                          rulesReg('plus'),
                        ],
                      })(<Input type="text" autocomplete="off" placeholder="提前提醒时间"/>)}
                  </FormItem>
                </Col>
              )}
            </Row>
            <Row gutter={{...rowGutterPxLayout}}>
              <Col {...colSpanLayout}>
                <FormItem
                  label="特色图片"
                  extra={type !== 'view' ? '支持png、jpg、gif, 大小不超过3MB' : ''}
                  {...formItemLayout}
                >
                  {type === 'view' ? (
                    <DefaultImage src={model.img} alt="" width="100px" height="70px"/>
                  ) : (
                    getFieldDecorator('img', {
                      initialValue: model.img,
                      rules: [
                        {
                          whitespace: true,
                          message: '不能包含空白符',
                        },
                        {
                          max: 1024,
                          message: '最长1024个字符',
                        },
                      ],
                    })(
                      <div className="clearfix">
                        <Upload
                          {...uploadPropsImg}
                          listType="picture-card"
                          onPreview={this.handleUploadPreview}
                        >
                          {this.state.fileImgList && this.state.fileImgList.length >= 1
                            ? null
                            : uploadButton}
                        </Upload>
                        <Modal
                          visible={this.state.previewVisible}
                          footer={null}
                          onCancel={() => this.setState({previewVisible: false})}
                        >
                          <img
                            alt="imgExample"
                            style={{width: '100%'}}
                            src={this.state.previewImage}
                          />
                        </Modal>
                      </div>
                    )
                  )}
                </FormItem>
              </Col>

              {/*<Col {...colSpanLayout}>
            <FormItem label="tenantId多租户使用" {...formItemLayout}>
              {type === 'view'
                ? model.tenantId
                : getFieldDecorator('tenantId', {
                  initialValue: model.tenantId,
                  rules: [
                    {
                      required: true,
                      message: 'tenantId多租户使用必填',
                    },
                    rulesReg('number'),
                    //rulesRemote('POST', getWebPath() + 'promotionsseckill/checkTenantId', {
                    //    roleNameOldValue: this.getPropsByKey('tenantId'),
                    //    IsTenantIdAdd: type === 'add',
                    //}),
                  ],
                })(
                  <Input
                    type="text"
                    autocomplete="off"
                    {...inputCodeDisabled}
                    placeholder="tenantId多租户使用"
                  />
                )}
            </FormItem>
          </Col>*/}
            </Row>
          </Card>

          {/*活动介绍*/}
          <Card
            bordered
            // hoverable
            size="small"
            bodyStyle={{paddingBottom: 10}}
            style={{marginBottom: 20}}
            title="活动介绍"
          >
            <Col {...colSpanLayout}>
              <FormItem {...formItemLayout}>
                {type === 'view'
                  ? model.brief
                  : getFieldDecorator('brief', {
                    initialValue: model.brief,
                    rules: [
                      /*   {
                         required: true,
                         message: '活动设置-活动简介<可选>必填',
                       },*/
                      {
                        whitespace: true,
                        message: '不能包含空白符',
                      },
                      {
                        max: 1024,
                        message: '最长1024个字符',
                      },
                    ],
                  })(<TextArea maxlength={1024} rows={5} placeholder="活动简介"/>)}
              </FormItem>
            </Col>
            {/* {getFieldDecorator('brief', {
            initialValue: BraftEditor.createEditorState(model.brief),
            rules: [
              // {
              //   required: true,
              //   message: '介绍必填',
              // },
              {
                max: 1024,
                message: '最长1024个字符',
              },
            ],
          })(
            <BraftEditor
              className={styles.my_editor}
              placeholder="请输入活动介绍"
              onChange={this.handleChange}
              extendControls={extendControls}
              {...inputCodeDisabledForView}
              {...editorProps}
            />
          )}*/}
          </Card>

          {/*秒杀商品*/}
          <Card
            bordered
            // hoverable
            size="small"
            bodyStyle={{paddingBottom: 10}}
            style={{marginBottom: 20}}
            title="参加活动的商品"
          >
            {type !== 'view' && (
              <Row gutter={{...rowGutterPxLayout}}>
                <Button
                  style={{marginLeft: 10}}
                  type="primary"
                  icon="plus"
                  onClick={this.showProductAddFrom}
                >
                  添加商品
                </Button>
              </Row>
            )}
            <Row gutter={{...rowGutterPxLayout}}>
              <Table
                style={{marginTop: 10}}
                columns={columns}
                bordered
                // dataSource={this.props.model.seckillProductList}
                dataSource={this.state.seckillProductList}
              />
            </Row>
          </Card>
        </Form>

        <ProductAddForm
          key={Math.random()}
          visible={this.state.productAddFromVisible}
          seckillProductList={this.state.seckillProductList}
          onCancel={() => {
            this.productAddForm.props.form.resetFields();
            this.setState({productAddFromVisible: false});
          }}
          onOk={seckillProductList => {
            // eslint-disable-next-line react/no-access-state-in-setstate
            let datasources = this.state.seckillProductList;
            if (datasources === undefined) {
              datasources = [];
            }
            datasources.push(seckillProductList);
            this.setState({
              seckillProductList: datasources,
            });
            this.setState({
              productAddFromVisible: false,
            });
          }}
          wrappedComponentRef={inst => {
            this.productAddForm = inst;
          }}
        />
      </Fragment>
    );
  }
}

/* eslint-disable no-class-assign */
//无更多的绑定， 请用 @Form.create() 注解替换
EditForm = Form.create({})(EditForm);
